package leetcode.day_2020_11_16_11_22;

import java.util.ArrayList;
import java.util.List;

public class L_8 {
    public static void main(String[] args) {
        String s = "-+12";
        System.out.println(myAtoi(s));
    }

    public static int myAtoi(String s) {
        if(s.length()==0)
            return 0;
        char[] sArr = s.toCharArray();
        if(sArr[0]!='-' && sArr[0]!='+' && sArr[0]!=' ' && (sArr[0]<'0' || sArr[0]>'9'))
            return 0;
        List<Character> list = new ArrayList<>();
        for(int i=0; i<sArr.length; i++){
            if(checkContion(sArr[i])) {
                if (sArr[i]!=' ')
                    list.add(sArr[i]);
            }else {
                break;
            }
        }
        int size = list.size();
        int flag = 1;
        double sum = 0;
        for(Character c : list) {
            if(c=='-'){
                flag = -1;
            }else if(c=='+'){
                flag = 1;
            } else {
                sum = sum + Integer.parseInt(String.valueOf(c))*Math.pow(10, size-1);
            }
            size-- ;
        }
        if(sum * flag > Integer.MAX_VALUE){
            return Integer.MAX_VALUE;
        }else if(sum * flag < Integer.MIN_VALUE){
            return Integer.MIN_VALUE;
        }else {
            return (int)sum * flag;
        }
    }

    public static boolean checkContion(char c1) {
        if(' '==c1 || '-' == c1 || '+' == c1 || (c1>='0' && c1<='9'))
            return true;
        return false;
    }
}
